package com.gylang.print.pdf.test;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.gylang.print.pdf.test.docx.SampleDoc;
import org.docx4j.Docx4J;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.Document;

import javax.xml.bind.JAXBException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片盖章
 *
 * @author gylang
 * data 2021/6/3
 */
public class SealPdf {


	public static void main(String[] args) throws FileNotFoundException, Docx4JException, JAXBException {

		//
		String document = IoUtil.read(new FileInputStream(SealPdf.class.getResource("/seal.xml").getPath()), StandardCharsets.UTF_8);

		Map<String, String> data = new HashMap<>();
		data.put("name", "全球GPBC冠军");
		data.put("userInfo", "猪猪侠");
		data.put("content", "恭喜你获得本次全球大型养猪技能竞赛-GPBC(GOLDEN-PIG-BREED-CHAMPIONSHIP)冠军。");

		// doc4j 占位替换
		StringBuilder codeOrg = new StringBuilder();
		String code = "证书编号：" + "3124197423572389573293527412";
		String org = "发证机构名称：" + "小猪佩奇";
		codeOrg.append(code).append("        ").append(org);
		StringBuilder expireCreate = new StringBuilder();

		String expire = "证书有效期至：" + "2022年2月22日";
		String create = "发证日期：" + "2020年2月22日";

		expireCreate.append(expire).append("        ").append(create);
		data.put("code_org", codeOrg.toString());
		data.put("expire_create", expireCreate.toString());
		String xml = StrUtil.format(document, data);
		Document outDoc = (Document) XmlUtils.unwrap(XmlUtils.unmarshalString(xml));
		WordprocessingMLPackage aPackage = WordprocessingMLPackage.createPackage();
		aPackage.getMainDocumentPart().setJaxbElement(outDoc);
		// 获取图片渲染
		Docx4J.toPDF(aPackage, new FileOutputStream(SampleDoc.BASE + "seal/seal2pdf" + System.currentTimeMillis() + ".pdf"));
	}
}
